package com.android.phoenix.util;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;





import com.android.phoenix.MainApplication;

import android.content.Context;
import android.content.res.AssetManager;

public class Ray_FileUtils {
	public static void cleanCacheDir() {
		File dir = new File(MainApplication.CACHE_DIR);
		File[] files = dir.listFiles();
		if (files != null) {
			for (File f : files) {
				f.delete();
			}
		}

//		dir = MainApplication.getContext().getCacheDir();
//		files = dir.listFiles();
//		if (files != null) {
//			for (File f : files) {
//				f.delete();
//			}
//		}
	}

	public static String getExtName(String path) {
		int j = path.lastIndexOf('.');
		if (j != -1) {
			return path.substring(j + 1);
		}

		return null;
	}

	public static boolean saveDataToFile(String path, byte[] data) {
		return saveDataToFile(new File(path), data);
	}

	public static boolean saveDataToFile(File file, byte[] data) {
		FileOutputStream f = null;
		try {
			f = new FileOutputStream(file);
			f.write(data);

			return true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeSilently(f);
		}

		return false;
	}

	public static boolean copyFile(File srcFile, File dstFile) {
		FileInputStream is = null;
		FileOutputStream os = null;
		try {
			is = new FileInputStream(srcFile);
			os = new FileOutputStream(dstFile);

			return copyStream(is, os);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			closeSilently(is);
			closeSilently(os);
		}

		return false;
	}

	public static boolean copyStream(InputStream is, OutputStream os) {
		byte[] buffer = new byte[1024];
		try {
			while (true) {
				int bytes = is.read(buffer);
				if (bytes <= 0)
					break;

				os.write(buffer, 0, bytes);
			}

			return true;
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			buffer = null;
		}

		return false;
	}

	public static void closeSilently(Closeable c) {
		if (c == null)
			return;
		try {
			c.close();
		} catch (Throwable t) {
			// do nothing
		}
	}

	public static boolean dumpAssetFile(Context context, String name,
			File outFile) {
		FileOutputStream os = null;
		InputStream is = null;

		try {
			AssetManager am = context.getAssets();

			outFile.getParentFile().mkdirs();

			os = new FileOutputStream(outFile);
			is = am.open(name, AssetManager.ACCESS_RANDOM);

			return Ray_FileUtils.copyStream(is, os);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			Ray_FileUtils.closeSilently(is);
			Ray_FileUtils.closeSilently(os);
		}

		return false;
	}

	public static byte[] calcFileMD5(File file) {
		byte[] result = null;
		byte[] buff = null;
		FileInputStream is = null;

		try {
			MessageDigest algorithm = MessageDigest.getInstance("md5");
			algorithm.reset();

			buff = new byte[1024];
			is = new FileInputStream(file);
			while (true) {
				int count = is.read(buff);
				if (count <= 0) {
					break;
				}

				algorithm.update(buff, 0, count);
			}

			result = algorithm.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (is != null) {
			try {
				is.close();
				is = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		buff = null;

		return result;
	}

	public static String readFileSection(File file, String begTag, String endTag) {
		InputStreamReader isr = null;
		try {
			isr = new InputStreamReader(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		if (isr == null) {
			return null;
		}

		StringBuilder sb = new StringBuilder();
		boolean found_begin = false;
		final int pre_fix_len = Math.max(begTag.length(), endTag.length());

		char[] buff = new char[pre_fix_len + 0x1000];
		while (true) {
			int bytes = -1;
			try {
				bytes = isr.read(buff, pre_fix_len, 0x1000);
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (bytes <= 0) {
				break;
			}

			String str = new String(buff, 0, bytes + pre_fix_len);
			if (!found_begin) {
				int i = str.indexOf(begTag);
				if (i != -1) {
					int j = str.indexOf(endTag);
					if (j != -1) {
						sb.append(str.substring(i, j + endTag.length()));
						break;
					}

					sb.append(str.substring(i, str.length()));
					found_begin = true;
				}
			} else {
				int j = str.indexOf(endTag);
				if (j != -1) {
					sb.append(str.substring(pre_fix_len, j + endTag.length()));
					break;
				}

				sb.append(str.substring(pre_fix_len, str.length()));
			}

			for (int i = 0, j = bytes; i < pre_fix_len; i++, j++) {
				buff[i] = buff[j];
			}
		}

		try {
			isr.close();
			isr = null;
		} catch (IOException e) {
			e.printStackTrace();
		}

		return sb.length() != 0 ? sb.toString() : null;
	}
	
	/**
	 * 
	 * @Title: saveStringToFile
	 * @Description: TODO(保存字符串到文件中)
	 * @author: Administrator
	 * @date: 2015年1月26日 下午9:30:04
	 * @param path
	 * @param str
	 * @return
	 */
	public static boolean saveStringToFile(String path ,String str ){
	    boolean result = false;
	    FileWriter fw = null;
	    String path1=MainApplication.RECORD_CACHE_DIR+path+".txt";
	    try {
	        File file = new File(path1);
	        fw = new FileWriter(file);
	        fw.write(str);
	        fw.close();
	        result = true;
	    } catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	        try {
	        fw.close();
	        } catch (Exception e) {
	        e.printStackTrace();
	        }
	    }
	 
	    return result;
		
	}
	/**
	 * 
	 * @Title: readStringFromFile
	 * @Description: TODO(从文件中读取字符串)
	 * @author: Administrator
	 * @date: 2015年1月26日 下午9:31:15
	 * @param filename
	 * @return
	 */
	public static String readStringFromFile(String filename) {
		String path=MainApplication.RECORD_CACHE_DIR+filename+".txt";
		return readStringFromFile(new File(path));
	}
	
	public static String readStringFromFile(File file) {
		
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(new FileReader(file));
			String buffer = null;
			String str;
			int i=0;
			while ((str = bufferedReader.readLine()) != null) {
				if(i==0)
				buffer = str;
				else {
					buffer+=str;
				}
				i++;
			}
			bufferedReader.close();
			return buffer;
		} catch (FileNotFoundException e) {
			if (bufferedReader != null)
				try {
					bufferedReader.close();
				} catch (IOException e1) {
				}
		} catch (IOException e) {
			try {
				if (bufferedReader != null)
					bufferedReader.close();
			} catch (IOException e1) {
			}
		}
		return null;
	}

	public static byte[] readByteFromFile(File file) {
		byte[] buffer = new byte[(int) file.length()];
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
			fileInputStream.read(buffer);
			fileInputStream.close();
			return buffer;
		} catch (FileNotFoundException e) {
			if (fileInputStream != null)
				try {
					fileInputStream.close();
				} catch (IOException e1) {
				}
		} catch (IOException e1) {
			if (fileInputStream != null)
				try {
					fileInputStream.close();
				} catch (IOException e) {
				}
		}
		return null;
	}

	public static void delDir(File file) {
		if(file.isFile()){
            file.delete();
            return;
        }
        if(file.isDirectory()){
            File[] childFile = file.listFiles();
            if(childFile == null || childFile.length == 0){
                file.delete();
                return;
            }
            for(File f : childFile){
            	delDir(f);
            }
            file.delete();
        }
	}
}